#include "PDB2Dyn.h"

#include <BALL/KERNEL/system.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/FORMAT/PDBFile.h>
#include "DYNAMOFile.h"
#include <BALL/STRUCTURE/fragmentDB.h>

PDB2Dyn::PDB2Dyn(const std::string& infile_name)
    : infile_name(new BALL::String(infile_name)), pdb_file(new BALL::PDBFile(infile_name))
{ }

void PDB2Dyn::open()
{
    if (pdb_file->bad())
    {
        throw std::invalid_argument("Cannot read input PDB file");
    }

    BALL::String outfile_name(*infile_name);
    outfile_name.reverse();
    outfile_name = outfile_name.after(".");
    outfile_name.reverse();
    outfile_name = outfile_name + ".xml";
    out_fname = outfile_name;

    dyna_file = new BALL::DYNAMOFile(outfile_name, std::ios::out);
    if (dyna_file->bad())
    {
        throw std::invalid_argument("Cannot create output Dynamo file");
    }
}

int PDB2Dyn::convert()
{
    open();

    BALL::System system;
    (*pdb_file) >> system;
    pdb_file->close();

    BALL::FragmentDB db("");
    system.apply(db.normalize_names);
    system.apply(db.build_bonds);

    (*dyna_file) << system;
    dyna_file->close();

    return system.countAtoms();
}

const std::string& PDB2Dyn::getOutFname() const
{
    return out_fname;
}

